import ImportData from "@/components/ImportData";
import { s_getcommontableinfoBycondition, s_getSelectData, s_getTableInfo, s_operateInfo, s_updateInfo } from "@/services/basis";
import { ActionType, ProCard, ProColumns, ProForm, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from "@ant-design/pro-components";
import { Button, Col, message, Modal, Row, Space, Tabs, TabsProps } from "antd";
import { useRef, useState } from "react";
import { useModel } from "@umijs/max";

const App:React.FC=()=>{
    const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);
    const [selectedRecords2,setSelectedRecords2]=useState<DataType2[]>([]);
    const [open,setOpen]=useState(false);
    const [open2,setOpen2]=useState(false);
    const [etype,setEtype]=useState(1);
    const [etype2,setEtype2]=useState(1);

    const [craftOption,setCraftOption]=useState([{}]);

    const [params,setParams]=useState({});
    const [tabsKey,setTabsKey]=useState('param');

    const form_ref=useRef<ProFormInstance>();
    const form_ref2=useRef<ProFormInstance>();
    const table_ref=useRef<ActionType>();
    const table_ref2=useRef<ActionType>();

    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);
     const [selectedLineKeys2,setSelectedLineKeys2]=useState<any[]>([]);
     const { initialState, setInitialState } = useModel('@@initialState');

    interface DataType{
        // x_id,id,code,name,version,operate_time,operater_id,operater_name,
        x_id?:number,id?:number,code?:string,name?:string,version?:string,
        operate_time?:string,operater_id?:number,operater_name?:string,type?:number,
    };

    const columns:ProColumns<DataType>[]=[
        {dataIndex:'id',title:'ID',hidden:true}, {dataIndex:'code',title:'工序编码'},
        {dataIndex:'name',title:'工序名称'}, {dataIndex:'version',title:'版本'},
        {dataIndex:'type',title:'类型',valueType:'select',
            valueEnum:{1:{text:'加工'},2:{text:'运输'},3:{text:'等待'},4:{text:'质检'}}
        },
        {dataIndex:'operate_time',title:'时间',hidden:true},
        {dataIndex:'operater_id',title:'操作员ID',hidden:true}
    ];

    interface DataType2{
        // id,code,name,usetype,data_type,data_default,
        id?:number,code?:string,name?:string,type?:number,status?:number,
    };

    const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'id',title:'ID'},{dataIndex:'code',title:'工作组编码'},
        {dataIndex:'name',title:'工作组名称'},
        {dataIndex:'type',title:'类型',valueType:'select',
            valueEnum:{1:'技术',2:'设备',3:'工装模具',4:'材料',5:'操作人'}
        },
        {dataIndex:'status',title:'状态',valueType:'radio',
            valueEnum:{1:{text:'正常'},2:{text:'冻结'},3:{text:'删除'}}
        }
         
    ];

    const items:TabsProps['items']=[
        {
            key:'param',
            label:'分配工作组',
            children:<>
               <ProTable<DataType2> 
                  search={false}
                  options={false}
                  columns={columns2}
                  rowKey='id'
                  scroll={{y:600}}
                  actionRef={table_ref2}
                   rowSelection={{
                   type:'radio',
                   selectedRowKeys:selectedLineKeys2,
                   onChange(selectedRowKeys, selectedRows, info) {
                        setSelectedRecords2(selectedRows);
                        setSelectedLineKeys2(selectedRowKeys);
                    },
                 }}
              onRow={(record)=>{
                return {
                   onClick:()=>{
                      const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedLineKeys2([k]);
                     setSelectedRecords2([record]);
              },
            }
           }}
                 request={async ()=>{
                    const x=await s_getTableInfo({x_id:1,source:'v_craft_card_detail',
                           id:selectedRecords.length==0?0:selectedRecords[0].id});
                    return {
                        data:x.data,
                        success:true,
                    }
                 }}
               />
            </>
        },
        // {
        //     key:'option',
        //     label:'工艺选项',
        
        //     children:<>
        //     {/* {JSON.stringify(selectedRecords)} */}
        //        <ProForm layout="horizontal" labelAlign="left" labelCol={{offset:0,span:7}} labelWrap 
        //           formRef={form_ref2}
        //           submitter={false} style={{marginLeft:50}} 
        //         //   initialValues={craftOption==undefined||craftOption.length==0?{}:{...craftOption[0]}}
        //           >
        //             <Row gutter={8}>
        //               <Col span={8}>
        //               {/* <ProFormRadio.Group name='type' label='类型' width={200} 
        //                    options={[{value:1,label:'加工'},{value:2,label:'运输'},
        //                              {value:3,label:'等待'},{value:4,label:'质检'}]}
        //                  /> */}
        //               <ProFormRadio.Group name='iskaigong' label='是否必先开工' width={200} 
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //                />
        //               <ProFormRadio.Group name='istouliao' label='是否投料校验' width={200} 
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormRadio.Group name='ispaigong' label='是否必派工' width={200} 
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormRadio.Group name='ischeckself' label='是否自检' width={200} 
        //                 options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormRadio.Group name='ischeck2next' label='是否自检合格才转下工序' width={200} 
        //                 options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />

        //               <ProFormRadio.Group name='isfangong' label='是否可返工' width={200} 
        //                    options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormSelect name='default2fangongcraft' label='默认转返工工序' width={200} 
        //                  showSearch
        //                  options={[{value:1,label:'列出工序清单'}]}
        //               />
        //              </Col>  
        //               <Col span={8}>
        //               <ProFormRadio.Group name='istofreecraft' label='是否可转自由工序' width={200}
        //                options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
                      
        //               <ProFormRadio.Group name='default2freecraftback' label='默认自由工序返回' width={200} 
        //                   options={[{value:1,label:'本工序'},{value:1,label:'下工序'},{value:3,label:'结束'}]}
        //               />
        //               <ProFormRadio.Group name='iscount' label='是否计件' width={200}
        //                    options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormRadio.Group name='counttype' label='计件类型' width={200} 
        //                   options={[{value:1,label:'个人'},{value:2,label:'班组'}]}
        //               />
                      
        //               <ProFormRadio.Group name='isbaogong' label='是否必报工' width={200}
        //                    options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormRadio.Group name='isbaogong2next' label='是否报工后自动转下工序' width={200} 
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormRadio.Group name='iscaifenshuliang' label='是否报工可拆分数量' width={200} 
        //                    options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
                                            
        //               <ProFormRadio.Group name='ischangchu' label='是否产出' width={200} 
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               </Col>
        //               <Col span={8}>
        //               <ProFormRadio.Group name='isbaogong2ware' label='是否报工即入库' width={200}
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormSelect name='defalutbaogong2ware' label='默认报工仓库' width={200} 
        //                   showSearch
        //                   request={async ()=>{
        //                         const x=await s_getSelectData({x_id:1,source:'base2_ware'});
        //                         return x.data;
        //                         }}
        //               />
        //               <ProFormRadio.Group name='isbaofei' label='是否可报废' width={200} 
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
                
        //               <ProFormRadio.Group name='isbaofei2ware' label='报废是否必入库' width={200}
        //                   options={[{value:0,label:'否'},{value:1,label:'是'}]}
        //               />
        //               <ProFormSelect name='defaultbaofei2ware' label='默认报废仓库' width={200} 
        //                   showSearch
        //                   request={async ()=>{
        //                      const x=await s_getSelectData({x_id:1,source:'base2_ware'});
        //                      return x.data;
        //                      }}
        //               />

        //               <ProFormText name='standarseconds' label='标准时长/秒' width={200} />
        //               <ProFormText name='maxseconds' label='最大时长/秒' width={200} />
        //               </Col>
        //             </Row> 
        //         </ProForm>

        //     </>,
        // },
    ];

    //新增工序卡
    function add(){
        setEtype(1);
        setOpen(true);
    };
    //编辑工序卡片
    function edit(){
        if(selectedRecords.length==0)
            message.warning('请先选择要编辑的卡片');
        else{
            setEtype(0);
            setOpen(true);
        };
    };
    //保存工序卡片
    async function save(){
       const fdata=form_ref.current?.getFieldsValue();
    //    alert(JSON.stringify(fdata));
       const x=await s_updateInfo({x_id:1,operater_id:initialState?.currentUser?.userid,etype,source:'craft_card',fdata});
       if(x.success){
          table_ref.current?.reloadAndRest?.();
          message.success('保存成功');
          setOpen(false);
          setEtype(1);
       }else
          message.error('保存失败，请联系管理员');
    };

    // 当选择卡片时，自动带出相应的工艺参数，和选项
    async function getOption(id:any){
        const x=await s_getcommontableinfoBycondition({x_id:1,source:'craft_card_option',tdata:{id}});
        //   alert(JSON.stringify(x.data[0]));
        var d={}; 
        if(x.data[0].length>0){
            d=x.data[0][0]; 
        };
            form_ref2.current?.resetFields();
            form_ref2.current?.setFieldsValue({...d});
    };

    //保存卡片的选项值-----2025-03-21
    async function saveOption(){
        var fdata=form_ref2.current?.getFieldsValue();
        fdata={...fdata,card_id:selectedRecords.length>0?selectedRecords[0].id:0};
        // alert(JSON.stringify(fdata));
        const x=await s_updateInfo({source:'craft_card_option',x_id:1,operater_id:initialState?.currentUser?.userid,etype:0,fdata});
        if(x.success){
            message.success('保存成功');
        }else
            message.error('保存失败');
    }

     async function operate(otype:number){
        if(selectedRecords2.length==0)
            message.warning('请先选择要操作的记录');
        else{
            const id=selectedRecords2[0].id;
            //s_operateInfo({source:'base_ware',operater_id:initialState?.currentUser?.userid,type:tabKey,otype,id})通用表格操作冻结删除
            const x=await s_operateInfo({source:'craft_card_detail',x_id:1,operater_id:initialState?.currentUser?.userid,otype,id});
    
            if(x.success){
                message.success('更新成功。');
                table_ref2.current?.reloadAndRest?.();
            }else
               message.error('更新失败，请联系管理员。');
        };
    };
        
    // 新增或编辑卡片所包含的工作组
   function addWorkgroup(){
      if(selectedRecords.length==0)
        message.warning('请先选择工序卡片');
      else{
        setEtype2(1);
        setOpen2(true);
      };
   };
   function editWorkgroup(){
     if(selectedRecords2.length==0)
        message.warning('请先选择要修改的项目');
    else{
        setEtype2(0);
        setOpen2(true);
    }
   }

//    保存工作组
async function saveDetail(){
    var fdata=form_ref2.current?.getFieldsValue();
     
    // alert(JSON.stringify(fdata));
    const x=await s_updateInfo({x_id:1,source:'craft_card_detail',etype:etype2,fdata});
    if(x.success){
        message.success('保存成功');
        table_ref2.current?.reloadAndRest?.();
    }else
        message.error('保存失败，请联系管理员');
};

    // 窗体======================================================================================================
    return <>
       <Row gutter={8}>
           <Col span={8}>
               <ProCard title='工序卡片' style={{height:'85vh',overflow:'auto'}}
                  extra={<Space>
                    <Button onClick={()=>add()}>新增工序</Button>
                    <Button onClick={()=>edit()}>编辑工序</Button>
                    <ImportData  x_id={1} source='importdata' tdata={{data:'craft_card'}} operater_id={1} />
                  </Space>}
               >
                   <ProTable<DataType> 
                       search={false}
                       columns={columns}
                       options={false}
                       rowKey='id'
                       scroll={{y:600}}
                       request={async (params)=>{
                          const x=await s_getTableInfo({source:'v_craft_card',x_id:1,id:0});  //通用的表格取数函数
                          return{
                            data:x.data,
                            success:true,
                             }
                       }}
                     actionRef={table_ref}
                     rowSelection={{
                             type:'radio',
                             selectedRowKeys:selectedLineKeys,
                             async onChange(selectedRowKeys, selectedRows, info) {
                                 setSelectedRecords(selectedRows);
                                 setSelectedLineKeys(selectedRowKeys);
                                 getOption(selectedRowKeys.length>0?selectedRowKeys[0]:0);
                                //   form_ref2.current?.setFieldsValue({...craftOption[0]});
                                //  form_ref2.current?.resetFields();
                                 table_ref2.current?.reloadAndRest?.();
                                //  //更新选项
                                //  const y=await s_getTableInfo({x_id:1,source:'craft_card_option',
                                //         id:selectedRowKeys.length>0?selectedRowKeys[0]:0}); 
                                //  if(y.data!=undefined&&y.data!=undefined&&y.data.length>0){
                                //      form_ref2.current?.setFieldsValue({...y.data[0]});
                                //  }else
                                //      form_ref2.current?.setFieldsValue({});
                             },
                     }}
       onRow={(record)=>{
             return {
               onClick:()=>{
                const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                    setSelectedRecords([record]);
                    setSelectedLineKeys([k]);
                   getOption(selectedLineKeys.length>0?selectedLineKeys[0]:0);
                                //   form_ref2.current?.setFieldsValue({...craftOption[0]});
                                //  form_ref2.current?.resetFields();
                   table_ref2.current?.reloadAndRest?.();
              },
            }
           }}
                    />
               </ProCard>
           </Col>
           <Col span={16}>
              <ProCard title='卡片归属工作组' style={{height:'85vh',overflow:'auto'}}
                   extra={<Space>
                       <Button onClick={()=>addWorkgroup()} hidden={tabsKey=='option'}>新增分配</Button>
                       <Button onClick={()=>editWorkgroup()} hidden={tabsKey=='option'}>编辑分配</Button>
                       <Button onClick={()=>operate(2)} hidden={tabsKey=='option'}>冻结</Button>
                       <Button onClick={()=>operate(3)} hidden={tabsKey=='option'}>删除</Button>
                       <Button onClick={()=>operate(1)} hidden={tabsKey=='option'}>恢复</Button>
                       {/* <Button onClick={()=>saveOption()} hidden={tabsKey=='param'}>保存选项</Button> */}
                   </Space>}
               >
                 <Tabs items={items} onTabClick={(e)=>setTabsKey(e)}/>
              </ProCard>
           </Col>
       </Row>
       {/* //iskaigong,istouliao,ispaigong,ischeckself,ischeck2next,isfangong,default2fangongcraft,
 //istofreecraft,default2freecraftback,iscount,counttype,isbaogong,isbaogong2next,iscaifenshuliang,
//ischangchu,isbaogong2ware,defalutbaogong2ware,isbaofei,defaultbaofei2ware,standarseconds,maxseconds */}
      {/* 增减工序窗口---------------------------------------------------------- */}
      <Modal  open={open}  destroyOnClose width={800} onCancel={()=>setOpen(false)} 
          onClose={()=>setOpen(false)} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
        >
          <ProCard title={etype==1?'新增工序卡片':'编辑工序卡片'} 
            extra={<Space>
                <Button onClick={()=>save()}>保存</Button>
                <Button onClick={()=>setOpen(false)}>退出</Button>
            </Space>}
          >
            <ProForm formRef={form_ref} submitter={false} layout="horizontal" labelAlign="left" labelWrap
               labelCol={{offset:0,span:5}}
               onFinish={save} style={{marginLeft:50}}
               initialValues={etype==0&&selectedRecords.length>0?{...selectedRecords[0]}
                    :{
                        type:1,status:1,operater_id:initialState?.currentUser?.userid
                    }}
            >
                <ProFormText name='id' hidden={true} />
                <ProFormText name='code' label='工序编码'  width={200}  
                     rules={[{required:true,message:'必填项'}]} />
                <ProFormText name='name' label='工序名称'  width={200} 
                     rules={[{required:true,message:'必填项'}]} 
                />
                <ProFormRadio.Group name='type' label='类型'
                     options={[{value:1,label:'加工'},{value:2,label:'运输'},
                        {value:3,label:'等待'},{value:4,label:'质检'},]}
                />
                <ProFormText name='version' label='版本'  width={200} />
                <ProFormSelect name='default_workcenter_id' label='默认生产中心' width={200}
                     showSearch
                     request={async ()=>{
                         const x=await s_getSelectData({x_id:1,source:'workcenter'});
                              return x.data;
                             }}
                />
                <ProFormSelect name='default_workgroup_id' label='默认工作组' width={200} 
                     showSearch
                     request={async ()=>{
                            const x=await s_getSelectData({x_id:1,source:'workgroup'});
                                 return x.data;
                         }}
                />
                <ProFormRadio.Group name='status' label='状态' 
                    options={[{value:1,label:'正常'},{value:2,label:'冻结'},{value:3,label:'关闭'}]} />
                <ProFormSelect name='operater_id' label='操作人' width={200}
                    showSearch
                    request={async ()=>{
                        const x=await s_getSelectData({x_id:1,source:'base_person'});
                             return x.data;
                     }}
                    /> 
            </ProForm>
        
         </ProCard> 
      </Modal>     
       {/* 工序卡片的工作组编辑 */}
       <Modal open={open2} destroyOnClose onCancel={()=>setOpen2(false)} onClose={()=>setOpen2(false)}
         width='60%' okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}>
          <ProCard title={etype2==1?'新增工作组':'编辑工作组'} style={{height:600}} 
             extra={<Space>
                <Button onClick={()=>form_ref2.current?.submit()}>保存</Button>
                <Button onClick={()=>setOpen2(false)}>退出</Button>
             </Space>}
            >
                <ProForm formRef={form_ref2} submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                    onFinish={()=>saveDetail()}
                    initialValues={etype2==1?{status:1,card_id:selectedRecords.length>0?selectedRecords[0].id:0,}
                          :{...selectedRecords2[0],
                            card_id:selectedRecords.length>0?selectedRecords[0].id:0,
                          }}
                >
                     <ProFormText name='card_id' hidden={true} />
                     <ProFormText name='id' hidden={true} />
                     <ProFormSelect name='workgroup_id' label='工作组' width={200}
                      rules={[{required:true,message:'必填项'}]}
                      showSearch
                      request={async ()=>{
                        const x=await s_getSelectData({x_id:1,source:'workgroup'});
                             return x.data;
                     }}
                     />
                    <ProFormRadio.Group name='status' label='状态' 
                      rules={[{required:true,message:'必填项'}]}
                      options={[{value:1,label:'正常'},{value:2,label:'冻结'},{value:3,label:'删除'}]} /> 

                </ProForm>

          </ProCard>
      </Modal>
    </>;
};

export default App;